package main.api;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Updates;
import main.*;
import main.database.AccountHelper;
import main.database.DatabaseMan;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Map;

import static main.RealPersonHelper.rpHash;

@RestController
public class ArticleCommentApi {
    @PostMapping("/api/publishartilecomment")
    public ResponseEntity<?> publishArticleComment(HttpServletRequest request) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        String account = AccountHelper.getAccountInfoFromUUID(uuid);

        boolean isLogin = true;
        if (account == null || account.isEmpty()) {
            isLogin = false;
        }

        String result;
        if (isLogin) {
            Map<String, String[]> map = request.getParameterMap();
            String content = null, fictionId = null, clientHash = null, captcha = null;
            if (map.containsKey("content")) {
                content = map.get("content")[0];
            }
            if (map.containsKey("fictionid")) {
                fictionId = map.get("fictionid")[0];
            }
            if (map.containsKey("clientHash")) {
                clientHash = map.get("clientHash")[0];
            }
            if (map.containsKey("captcha")) {
                captcha = map.get("captcha")[0];
            }

            if (content == null || content.isEmpty()) {
                result = ResponseHelper.createBasicJsonObject(404, "发布的内容不能是空的").toString();
            }
            else if (fictionId == null || fictionId.isEmpty()) {
                result = ResponseHelper.createBasicJsonObject(404, "发布评论时必须带上小说的ID").toString();
            }
            else if (clientHash == null || clientHash.isEmpty()) {
                result = ResponseHelper.createBasicJsonObject(404, "没有提供图形验证码信息").toString();
            }
            else {
                String rpHash = rpHash(captcha);

                if (rpHash.equals(clientHash)) {
                    try {
                        String lastCommentTime = CommentHelper.getLastCommentTime(uuid);
                        boolean canComment = false;

                        if (lastCommentTime.trim().equals("")) {
                            canComment = true;
                        } else {
                            Timestamp lastTime = Timestamp.valueOf(lastCommentTime);
                            if (TimeHelper.isTimeNMinutesBefore(lastTime, 10)) {
                                canComment = true;
                            }
                        }

                        if (canComment) {
                            String time = DateTimeHelper.getCurrentTimePretty();
                            content = StringHelper.replaceReturnWithBR(content);

                            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfCommentToArticle);
                            Document document = new Document("userid", uuid)
                                    .append("fictionid", fictionId)
                                    .append("comment", content)
                                    .append("createtime", time);

                            collection.insertOne(document);

                            //给用户加分
                            collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfUser);
                            Bson filter = new Document("uuid", uuid);
                            Bson update = Updates.inc("money", 1);
                            collection.updateOne(filter, update);

                            result = ResponseHelper.createBasicJsonObject(200, "ok").toString();
                        } else {
                            result = ResponseHelper.createBasicJsonObject(404, "讨论发送太频繁").toString();
                        }
                    } catch (Exception e) {
                        result = ResponseHelper.createBasicJsonObject(404, "数据库操作发生错误").toString();
                    }
                }
                else {
                    result = ResponseHelper.createBasicJsonObject(404, "验证码错误").toString();
                }
            }
        }
        else {
            result = ResponseHelper.createBasicJsonObject(404, "只有登录的用户才能发布评论").toString();
        }

        return ResponseEntity.ok(result);
    }
}
